<!--
  -    Copyright (c) 2018-2025, infomng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: infomng
  -->
<template>
  <div class="execution">
    <basic-container style="">
      <div style="width:70%;float: left;margin-bottom:20px;min-height: 600px;">
        <avue-crud
          ref="crud"
          :data="tableData"
          :permission="permissionList"
          :table-loading="tableLoading"
          :option="tableOption"
          @on-load=""
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @row-update="handleUpdate"
          @row-save="handleSave"
          @row-del="handleDel"
          @sortable-change="sortableChange">
          <template slot="menuLeft">
            <!--<el-button
              v-if="permissions.workorder_workordercps_export"
              class="filter-item"
              plain
              type="primary"
              size="small"
              icon="el-icon-download"
              @click="exportExcel">导出
            </el-button>-->
            <el-button  type="primary"  v-if=" lineInfo.lineStatus=='未生产'" @click="startProduction">开始生产<i class="el-icon-video-play el-icon--right"></i> </el-button>
            <el-button  type="primary"  v-if=" lineInfo.lineStatus=='生产中'" @click="pauseProduction">暂停<i class="el-icon-video-pause el-icon--right"></i> </el-button>
            <el-button  type="primary"  v-if=" lineInfo.lineStatus=='暂停中'" @click="continueProduction">继续生产<i class="el-icon-video-play el-icon--right"></i> </el-button>
          </template>
          <!--产线自定义搜索-->
          <template slot-scope="scope" slot="lineIdSearch">
            <div class="block">
              <el-select  v-model="lineId" filterable placeholder="请选择产线" style="width: 200px">
                <el-option
                  @click.native="chooseLine(item)"
                  v-for="item in lineList"
                  :label="item.realityLineName"
                  :value="item.id"
                  :key="item.id">
                </el-option>
              </el-select>
            </div>
          </template>
        </avue-crud>
    </div>
    <div style="width:28%;float: left;margin-bottom:20px;margin-left:10px;min-height: 600px;border-left:1px solid #cccccc ">
      <div style="margin-left: 20px" ><!--v-if=" lineInfo.lineStatus=='生产中'"-->
        <el-steps direction="vertical" :space="100" >
          <el-step v-for="item in workOrderProductionList" :title="item.workshopSection" status="process" icon="el-icon-setting">
            <template slot="description" >
              <span>工单信息：{{item.docNo }}<br/> 产品信息：{{item.workordeInfo}}</span>
            </template>
          </el-step>
        </el-steps>
      </div>
    </div>
    </basic-container>
  </div>
</template>

<script>
import { fetchList, addObj, putObj, delObj,
         getWorkOrderListByLineId,//获取产线下工单
         workOrderSort,//工单排序
         startLineProduction,//开始产线生产
         getWorkOrderProductionList,//产线下工单生产信息
         pauseLineProduction,//暂停产线生产
         continueLineProduction //继续生产
} from '@/api/workorder/workordercps'
import { getLineList} from '@/api/pfoc/realityproductlinemain' //获取产线集合
import { remote} from '@/api/admin/dict' //字典接口
import { sortableOption } from '@/const/crud/workorder/workordersort' //行拖拽排序option
import { mapGetters } from 'vuex'
import {validatenull} from "../../../util/validate";

export default {
  name: 'workordercps',
  data() {
    return {
      searchForm: {},
      tableData: [],
      tableLoading: false,
      tableOption: sortableOption,
      lineList:[],//产线集合
      lineId:null,//产线ID
      lineInfo:{},//产线数据对象
      workshopSectionList:[],//工段集合
      workOrderProductionList:[],//产线生产信息

    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.workorder_workordercps_add, false),
        delBtn: this.vaildData(this.permissions.workorder_workordercps_del, false),
        editBtn: this.vaildData(this.permissions.workorder_workordercps_edit, false)
      }
    }
  },
  created() {
      //获取产线集合
      this.getLineListData();

  },
  methods: {
    //产线选择
    chooseLine(row){
        this.lineId = row.id;//产线ID
        this.lineInfo = row;//当前选择的产线对象
        this.getList();//获取当前产线下的未完工的排序工单
    },
    //获取当前产线下的工单生产信息
    getWorkOrderProductionListData(){
        getWorkOrderProductionList(this.lineId,this.lineInfo.lineStatus).then(response => {
            this.workOrderProductionList = response.data.data
        })

    },
    // 工单排序列表查询
    getList() {
      if(this.validatenull(this.lineId)){
          this.$message.warning("请选择产线。")
          return;
      }
      this.tableLoading = true
        //根据产线ID查询产线下工单
       getWorkOrderListByLineId(this.lineId).then(response => {
        this.tableData = response.data.data
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      });
      this.getWorkOrderProductionListData();//刷新工单生产信息
    },
    // 删除
    handleDel: function(row, index) {
      this.$confirm('是否确认删除ID为' + row.id, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    // 更新
    handleUpdate: function(row, index, done, loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading()
      })
    },
    // 保存
    handleSave: function(row, done, loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading()
      })
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    // 当前页发生改变事件
    currentChange(current) {
      // this.page.currentPage = current
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form
      // this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    // 刷新事件
    refreshChange() {
      this.getList(this.page)
    },
    //  导出excel
    exportExcel() {
      this.downBlobFile('/workorder/workordercps/export', this.searchForm, 'workordercps.xlsx')
    },

    //获取产线集合
    getLineListData(){
        getLineList().then(response => {
            this.lineList = response.data.data;
        })
    },
    //获取工段
    getWorkshopSectionListData(){
        remote("workshop_section").then(response => {
            this.workshopSectionList=response.data.data;
        })
    },
    //拖拽排序
    sortableChange(oldindex, newindex, row, newList,oldList) {
        //生产中的产线拖拽时需要查看拖拽工单是否正在生产以及拖拽工单存排序的位置的工单是否正在生产
        if( this.lineInfo.lineStatus == "生产中"){
            //获取当前拖拽工单号
            var docNo  = row.docNo;
            var flg = false;//默认不存在
            //判断在当前工单生产信息中是否存在拖拽工单号
            for (var i=0; i< this.workOrderProductionList.length;i++){
                if(docNo==this.workOrderProductionList[i].docNo){
                    flg = true;//存在
                }
            }
            if(flg){//正在生产中的工单
                this.tableData = oldList;//返回原排序序列，不可拖拽
                this.$message.warning("当前排序工单正在生产中，不可进行排序。")
            }else{//不在生产中的工单
                //根据拖拽工单最新位置，判断该位置之前的工单是否正在生产，如果是生产中的工单则不可进行拖拽排序
                var flgOld = false;//默认新位置拖拽前工单在工单生产信息中不存在
                var oldIndexDocNo = oldList[newindex].docNo;//获取拖拽前的位置工单
                //判断在当前工单生产信息中是否存在拖拽工单号
                for (var i=0; i< this.workOrderProductionList.length;i++){
                    if(oldIndexDocNo==this.workOrderProductionList[i].docNo){
                        flgOld = true;//存在
                    }
                }
                if(flgOld){
                    this.tableData = oldList;//返回原排序序列，不可拖拽
                    this.$message.warning("当前排序工单更换位置的工单正在生产中，不可进行排序。")
                }else{
                    //循环数据列表为排序字段赋值
                    newList.forEach((item, index) => {
                        item.sortOrder=index;
                        newList[index] = item;
                    });
                    console.log("new:"+JSON.stringify(newList));
                    console.log("old:"+JSON.stringify(oldList));
                    var data={
                        workorderList:newList,
                    }
                    //提交
                    workOrderSort(data).then(response => {
                        this.tableData = newList;//更新产线下工单数据
                        this.$message.success("排序成功")
                    }).catch(() => {
                        this.$message.error("排序失败")
                    });
                }
            }

        }else{
            //循环数据列表为排序字段赋值
            newList.forEach((item, index) => {
                item.sortOrder=index;
                newList[index] = item;
            });
            // console.log("new:"+JSON.stringify(newList));
            // console.log("old:"+JSON.stringify(oldList));
            var data={
                workorderList:newList,
            }
            //提交
            workOrderSort(data).then(response => {
                this.tableData = newList;//更新产线下工单数据
                this.$message.success("排序成功")
            }).catch(() => {
                this.$message.error("排序失败")
            });
        }

    },
    //开始生产
    startProduction(){
        if(!this.validatenull(this.tableData)) {
            //开始生产改变产线状态为生产中、将当前产线排序工单第一个工单号存入工单生产情况表的第一个工段并下发工单数据到设备同时获取当前产线工段集合
            startLineProduction(this.lineId,"生产中").then(response => {
                // this.$message.success(response.data.data)
                this.lineInfo.lineStatus = "生产中";//改变产线状态
                //更新表数据以及工段信息
                this.getList();
            })
        }else{
            this.$message.warning("当前产线下暂无工单任务.")
        }
    },
    //暂停生产
    pauseProduction(){
        //暂停生产改变产线状态为暂停中，同时改变所有生产中的工单为暂停中
        pauseLineProduction(this.lineId,"暂停中").then(response => {
            this.lineInfo.lineStatus = "暂停中";//改变产线状态
            //更新表数据以及工段信息
            this.getList();
        })
    },
    //继续生产
    continueProduction(){
        //产线暂停后不管有无工单排序调整，全部按照最新的工单排序依次判断各个工单的生产状态以及各工段生产信息
        continueLineProduction(this.lineId,"生产中").then(response => {
            this.lineInfo.lineStatus = "生产中";//改变产线状态
            //更新表数据以及工段信息
            this.getList();
        })
    },
  }
}
</script>
